import React, {useEffect, useState} from 'react';
import {
    Input,
    Select,
    DatePicker,
    Button,
    Table,
    Pagination,
    Space,
    Popconfirm,
    Modal,
    notification,
    Tag,
    Tooltip
} from "antd";
import Header from "../components/Header";
import Store from "../components/Store";
import http from "../request"
import moment from "moment"
import {fieldGet} from "../common/common";
import Footer from "../components/Footer";
import Recycle from "../components/Recycle";
import ResizeableTitle from '../components/ResizableTitle';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

const Key = () => {
    const field = {store_id: '=', staff_id: '=', state: '=', number: 'like', obtain_time: 'range', oper_time: 'range'}
    const pageDefault = {page: 1, pageSize: 10}
    const [source, setSource] = useState([])
    const [columns, setcolumns] = useState([
        {
            title: '状态',
            dataIndex: 'state',
            width:80,
            align: 'center',
            render: e => {
                switch(e){
                    case 'stay': return <Tag color="red">在库</Tag>;
                    case 'lend': return <Tag color="orange">借出</Tag>;
                    case 'retreat': return <Tag color="lime">退还</Tag>;
                    case 'void': return  <Tag color="cyan">作废</Tag>;
                    default: return '';
                }
            }
        },
        {
            title: '钥匙类型',
            width:80,
            dataIndex: 'type',
            align: 'center',
        },
        {
            title: '房源编号',
            width:80,
            dataIndex: 'house_id',
            align: 'center',
        },
        {
            title: '房源地址',
            width:80,
            dataIndex: 'house_data',
            align: 'center',
            render: e => (
                <Tooltip>
                    <div className="u-line-1" style={{maxWidth: 150}}>{e?.estate_data?.detailed_address??''}</div>
                </Tooltip>
            )
        },
        {
            title: '钥匙编号',
            width:80,
            dataIndex: 'number',
            align: 'center',
        },
        {
            title: '所在门店',
            width:80,
            dataIndex: 'store_data',
            align: 'center',
            render: e => e?.name??''
        },
        {
            title: '归属人',
            width:80,
            dataIndex: 'staff_data',
            align: 'center',
            render: e => e?.nickname??''
        },
        {
            title: '收钥匙日期',
            dataIndex: 'obtain_time_text',
            width:80,
            align: 'center',
        },
        {
            title: '备注',
            width:80,
            dataIndex: 'memo',
            align: 'center',
            render: e => (
                <div className="u-line-1" style={{maxWidth: 120}}>{e}</div>
            )
        },
        {
            title: '最后操作人',
            width:80,
            dataIndex: 'oper_data',
            align: 'center',
            render: e => e?.nickname??''
        },
        {
            title: '最后操作日期',
            width:80,
            align: 'center',
            dataIndex: 'oper_time_text',
        },
        {
            title: '操作',
            align: 'center',
            render: e => (
                <Space size="middle">
                    <img className="u-btn" src={require('../assets/icon/icon-12.png').default} alt="" title="编辑" onClick={() => keysEdit(e.id)}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() => keysDel(e.id)}>
                        <img className="u-btn" src={require('../assets/icon/icon-13.png').default} alt="" title="删除" />
                    </Popconfirm>
                </Space>
            ),
        },
    ])
    const [form, setForm] = useState({})
    // 筛选-时间
    const [date, setDate] = useState({})
    const [pager, setPager] = useState(pageDefault)
    const [total, setTotal] = useState(0)
    const [selected, setSelected] = useState([])
    // 钥匙-新增-编辑
    const [keysModal, setKeysModal] = useState({show: !1, text: ''})
    const [keys, setKeys] = useState({})

    const [change, setchange] = useState(!0)

    // 回收站-列
    const backColumns = [
        {
            title: '状态',
            dataIndex: 'state',
            align: 'center',
            render: e => {
                switch(e){
                    case 'stay': return <Tag color="red">在库</Tag>;
                    case 'lend': return <Tag color="orange">借出</Tag>;
                    case 'retreat': return <Tag color="lime">退还</Tag>;
                    case 'void': return  <Tag color="cyan">作废</Tag>;
                    default: return '';
                }
            }
        }, {
            title: '钥匙类型',
            dataIndex: 'type',
            align: 'center',
        }, {
            title: '房源编号',
            dataIndex: 'house_id',
            align: 'center',
        }, {
            title: '房源地址',
            dataIndex: 'house_data',
            align: 'center',
            render: e => (
                <Tooltip>
                    <div className="u-line-1" style={{maxWidth: 150}}>{e?.estate_data?.detailed_address??''}</div>
                </Tooltip>
            )
        }, {
            title: '钥匙编号',
            dataIndex: 'number',
            align: 'center',
        }, {
            title: '所在门店',
            dataIndex: 'store_data',
            align: 'center',
            render: e => e?.name??''
        }, {
            title: '归属人',
            dataIndex: 'staff_data',
            align: 'center',
            render: e => e?.nickname??''
        }, {
            title: '收钥匙日期',
            dataIndex: 'obtain_time_text',
            align: 'center',
        }, {
            title: '备注',
            dataIndex: 'memo',
            align: 'center',
            render: e => (
                <div className="u-line-1" style={{maxWidth: 120}}>{e}</div>
            )
        }, {
            title: '最后操作人',
            dataIndex: 'oper_data',
            align: 'center',
            render: e => e?.nickname??''
        }, {
            title: '最后操作日期',
            dataIndex: 'oper_time_text',
            align: 'center',
        }
    ]

    useEffect(() => {
        keysGet()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pager])
    return (
        <React.Fragment>
            <Header navCur={3}/>
            <div className="Key page u-p-20 u-m-20">
                <div className="part-title">钥匙管理</div>
                <div className="u-flex u-flex-wrap">
                    <div className="u-flex u-m-l-20 u-m-t-20">
                        <div className="label">部门</div>
                        <Store value={[form.store_id, form.staff_id]} onChange={storeChange} className="u-m-l-10" />
                    </div>
                    <div className="u-flex u-m-l-20 u-m-t-20">
                        <div className="label u-m-l-20">状态</div>
                        <Select value={form.state} onChange={e => formChange('state', e)} allowClear placeholder="状态" className="u-m-l-10" style={{width: 120}}>
                            <Option value="stay">在库</Option>
                            <Option value="lend">借出</Option>
                            <Option value="retreat">退还</Option>
                            <Option value="void">作废</Option>
                        </Select>
                        <Input value={form.number} onChange={e => formChange('number', e.target.value)} placeholder="钥匙编号，梯" className="u-m-l-10" style={{width: 120}}/>
                    </div>
                    <div className="u-flex u-m-l-20 u-m-t-20">
                        <div className="label u-m-l-20">日期</div>
                        <Select value={date.name} onChange={e => dateType(e)} allowClear placeholder="日期" className="u-m-l-10" style={{width: 120}}>
                            <Option value="obtain_time">收钥匙日期</Option>
                            <Option value="oper_time">最后操作日期</Option>
                        </Select>
                        { date.value && <RangePicker value={[date.value[0]?moment(date.value[0]):undefined,date.value[1]?moment(date.value[1]):undefined]} onChange={(e, es)=>dateValue(es)} className="u-m-l-10" style={{width: 250}}/> }
                        { !date.value && <RangePicker value={[undefined,undefined]} onChange={(e, es)=>dateValue(es)} className="u-m-l-10" style={{width: 250}}/> }
                    </div>
                    <div className="u-flex u-m-l-20 u-m-t-20">
                        <Button size="mini" type="primary" onClick={search}>
                            <img src={require('../assets/icon/icon-6.png').default} alt=""/>
                            <span className="u-m-l-5 u-text-nowrap">搜索</span>
                        </Button>
                        <div className="u-btn u-flex u-m-l-20" onClick={reset}>
                            <img src={require('../assets/icon/icon-7.png').default} alt=""/>
                            <span className="u-m-l-5 u-text-nowrap">清空</span>
                        </div>
                    </div>
                </div>
                <div className="u-m-t-20">
                    <Recycle url='key' func={keysGet} columns={backColumns} change={setchange} className="u-m-l-20" />
                </div>
                <div className="u-m-t-20">
                    <Table bordered rowKey={e => e.id} rowSelection={{
                        selectedRowKeys: selected,
                        onChange(e){
                            setSelected(e)
                        }
                    }} onRow={record => ({
                        onDoubleClick: () => {
                            keysEdit(record.id)
                        }
                    })} size="small" components={{
                        header: {
                            cell: ResizeableTitle
                        }
                    }} scroll={{x: 1280}} dataSource={source} columns={columns.map((col, index) => {
                        return {
                            ...col,
                            onHeaderCell: (column) => ({
                                width: column.width,
                                onResize: (e, { size }) => {
                                    setcolumns((columns) => {
                                        const nextColumns = [...columns];
                                        nextColumns[index] = {
                                            ...nextColumns[index],
                                            width: size.width
                                        }
                                        return nextColumns;
                                    })
                                }
                            })
                        }
                    })} pagination={false}/>
                </div>
                <div className="u-flex u-row-between u-m-t-20">
                    <div>
                        <Button type="primary" size="small" onClick={() => modalShow(setKeysModal)}>
                            <div className="u-flex">
                                <img src={require('../assets/icon/icon-18.png').default} alt=""/>
                                <span className="u-m-l-5">新增</span>
                            </div>
                        </Button>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={keysDel}>
                            <Button className="u-m-l-20" type="primary" size="small" danger>
                                <div className="u-flex">
                                    <img src={require('../assets/icon/icon-19.png').default} alt=""/>
                                    <span className="u-m-l-5">删除</span>
                                </div>
                            </Button>
                        </Popconfirm>
                    </div>
                    <Pagination showQuickJumper current={pager.page} pageSize={pager.pageSize} total={total}  onChange={(page, pageSize) => setPager({page, pageSize})}/>
                </div>
            </div>
            <Footer/>

            <Modal title="钥匙管理" okText="保存" width={480} destroyOnClose maskClosable={false} visible={keysModal.show} onOk={keysConfirm} onCancel={keysCancel}>
                <div className="Modal">
                    <div className="u-flex">
                        <div className="label">钥匙类型</div>
                        <Select placeholder="状态" value={keys.type} onChange={e => keysChange('type', e)} className="u-m-l-10" style={{width: 120}}>
                            <Option value="机械钥匙">机械钥匙</Option>
                            <Option value="门卡钥匙">门卡钥匙</Option>
                            <Option value="密码钥匙">密码钥匙</Option>
                        </Select>
                        <div className="label u-m-l-10">状态</div>
                        <Select placeholder="状态" value={keys.state} onChange={e => keysChange('state', e)} className="u-m-l-10" style={{width: 120}}>
                            <Option value="stay">在库</Option>
                            <Option value="lend">借出</Option>
                            <Option value="retreat">退还</Option>
                            <Option value="void">作废</Option>
                        </Select>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">房源编号</div>
                        <Input placeholder="房源编号" value={keys.house_id} onChange={e => keysChange('house_id', e.target.value)} className="u-m-l-10" style={{width: 120}}/>
                        <div className="label u-m-l-10">收钥匙日期</div>
                        <DatePicker className="u-m-l-10" value={keys.obtain_time ? moment(keys.obtain_time) : ''} onChange={(dates,dateString)=>keysChange('obtain_time', dateString)} />
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">所在门店</div>
                        <Store value={[keys.store_id, keys.staff_id]} onChange={keysStoreChange} className="u-m-l-10" />
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label u-m-l-28">备注</div>
                        <TextArea placeholder="备注" value={keys.memo} onChange={e => keysChange('memo', e.target.value)} className="u-m-l-10" style={{width: 360, height: 70}} />
                    </div>
                </div>
            </Modal>
        </React.Fragment>
    )
    function keysGet(){
        if(change && JSON.parse(sessionStorage.getItem('key_list'))){
            const house = JSON.parse(sessionStorage.getItem('key_list'))
            for (const key in house.rows) {
                if (key*1 === pager.page) {
                    setSource(house.rows[key])
                    setTotal(house.total)
                    return
                }
            }
        }
        let newForm = {...form};
        if(date.name && date.value){
            newForm[date.name] = date.value.join(' - ')
        }
        http('key.index', {
            ...fieldGet(field, newForm, pager.page, pager.pageSize),
        }).then(res => {
            if(res.code === 1){
                const page = pager.page
                if(total && change){
                    let arr = JSON.parse(sessionStorage.getItem('key_list'))
                    arr.rows[page] = []
                    res.data.rows.forEach(i=>arr.rows[page].push(i))
                    sessionStorage.setItem('key_list',JSON.stringify(arr))
                    setchange(!0)
                    setSource(res.data.rows)
                    setTotal(res.data.total)
                    return
                }
                const data = {
                    total:res.data.total,
                    rows:{
                        [page]:res.data.rows
                    }
                }
                sessionStorage.setItem('key_list',JSON.stringify(data))
                setchange(!0)
                setSource(res.data.rows)
                setTotal(res.data.total)
            }
        })
    }
    // 日期的处理
    function dateType(e) {
        let newDate = {...date}
        newDate.name = e
        setDate(newDate)
    }
    function dateValue(e){
        let newDate = {...date}
        newDate.value = e
        setDate(newDate)
    }
    function formChange(name, value){
        let newForm = {...form}
        newForm[name] = value
        setForm(newForm)
    }
    function storeChange(store_id, staff_id){
        let newForm = {...form}
        newForm.store_id = store_id
        newForm.staff_id = staff_id
        setForm(newForm)
    }
    function search(){
        let page = {...pager}
        page.page = 1
        setPager(page)
    }
    function reset(){
        setForm({})
        setDate({})
    }
    function keysChange(name, value){
        let newKeys = {...keys}
        newKeys[name] = value
        setKeys(newKeys)
    }
    function keysStoreChange(store_id, staff_id){
        let newKeys = {...keys}
        newKeys.store_id = store_id
        newKeys.staff_id = staff_id
        setKeys(newKeys)
    }
    function keysConfirm(){
        let url = keys?.id ? 'key.edit' : 'key.add'
        http(url, {
            row: keys
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '添加成功'
                })
                setchange(!1)
                setKeys({})
                modalHide(setKeysModal)
                keysGet()
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
        })
    }
    function keysEdit(ids){
        http('key.one', {ids}).then(res => {
            if(res.code === 1){
                setKeys(res.data)
                modalShow(setKeysModal)
            }
        })
    }
    function keysCancel(){
        setKeys({})
        modalHide(setKeysModal)
    }
    function keysDel(id){
        let ids = id > 0 ? [id] : selected
        http('key.del', {ids}).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '删除成功'
                })
                setchange(!1)
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            keysGet()
        }).catch(err=>console.log(err))
    }
    function modalShow(func, text){
        func({show: !0, text})
    }
    function modalHide(func){
        func({show: !1, text: ''})
    }
}

export default Key;